<template>
  <el-dialog title="质量评分" :close-on-click-modal="false" :visible.sync="visible" width="95%">
    <el-table :data="markGroupList" :span-method="objectSpanMethod" border v-loading="loading"
              :header-cell-style="tableHeaderColor" style="width: 100%;border: 1px solid #3E8EF7" :cell-style="{'borderColor': '#3E8EF76f'}">
      <el-table-column prop="qualityCate" header-align="center" align="center" label="质量元素类别" width="150" >
        <template slot-scope="scope"><strong>{{scope.row.qualityCate}}</strong></template>
      </el-table-column>
      <el-table-column prop="scoreRadio" header-align="center" align="center" label="评分权重" width="100"></el-table-column>
      <el-table-column prop="type" header-align="center" align="center" label="错漏类型" width="100">
        <template slot-scope="scope">
          <strong>{{scope.row.type}}</strong>
          <span style="color: red" v-if="scope.row.type == 'A'">(-42)</span>
          <span style="color: red" v-if="scope.row.type == 'B'">(-12)</span>
          <span style="color: red" v-if="scope.row.type == 'C'">(-4)</span>
          <span style="color: red" v-if="scope.row.type == 'D'">(-1)</span>
        </template>
      </el-table-column>
      <el-table-column prop="count" header-align="center" align="center" label="错漏总数" width="100"></el-table-column>
      <el-table-column header-align="center" align="left" label="错漏情况具体描述">
        <template slot-scope="scope">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addMarkScoreHandle(scope.row)"></el-button>
          <el-row v-for="(score,index) in scope.row.scoreList" :key="scope.row.qualityCate + index" style="padding-top: 3px;">
            <el-col :span="17">
              <el-autocomplete v-model="score.description" :fetch-suggestions="((queryString,cb)=>{queryDescriptionSearch(queryString,cb,scope.row)})"
                               @select="((item)=>{handleDescriptionSelect(item,score)})" size="mini"
                               required="true" style="width: 100%" placeholder="错误描述">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.description }}</div>
                </template>
              </el-autocomplete>
            </el-col>
            <el-col :span="5">
              <div style="display: flex;padding-left: 5px;">
                <span style="width: 50px;line-height: 200%">个数:</span>
                <el-input v-model="score.num" size="mini" type="number" :min="0" class="item_input" @input="scoreChangeHandler"></el-input>
              </div>
            </el-col>
            <el-col :span="2">
              <el-button icon="el-icon-delete" type="danger" size="mini" @click="delMarkScoreHandle(scope.row,score.uuid)"></el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="right" label="总扣分" width="100">
        <template slot-scope="scope">
          <span style="color: red">-{{parseFloat(scope.row.itemsum).toFixed(2)}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div style="float: right">
      <strong>合计得分：</strong><strong style="color: #2D64B3">{{totalScore}}</strong>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false" plain>取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {stringIsNull,getUUID} from '@/utils'
  export default {
    data () {
      return {
        visible: false,
        loading: true,
        checkcontent: [
          // 19年检查内容
          '坐标系统、高程系统的正确性',
          '投影参数、转换参数的正确性',
          '起算数据及选用的正确性、可靠性',
          '控制测量成果',
          '平面坐标精度',
          '平面相对位置精度',
          '高程精度',
          '要素错误、缺漏情况',
          '属性错误、缺漏情况',
          '数据及结构的正确性',
          '图面表达质量',
          '表格表达质量',
          '计算质量',
          '技术文档表达质量',
          '资料完整性、规范性',
          // 20年检查内容
          '作业依据、原始资料（含行政审批资料）使用的正确性、有效性',
          '平面、高程基准（包括投影、转换参数）',
          '平面坐标精度',
          '相对位置（或边长）精度',
          '高程精度',
          '其他',
          '仪器及其使用的符合性',
          '作业内容、范围的符合性',
          '作业记录的规范性',
          '作业记录的正确性、完整性',
          '作业内容（要素、数据）错误情况',
          '作业内容（要素、数据）缺漏情况',
          '属性（定性、分类）错误情况',
          '属性（定性、分类）缺漏情况',
          '图面符号、线划、色彩表达的正确性',
          '图面注记内容及大小的正确性',
          '平差计算过程及结果正确性',
          '其他',
          '图面表达清晰性（符号、注记叠压等）',
          '成果表的清晰、完整、正确性',
          '技术文档内容的完整性',
          '技术文档内容的正确性、标准规范符合性',
          '图、文（表）一致性',
          '资料规整性（字体、大小、格式、页码、纸张大小）',
          '成果资料的齐全性'
        ],
        kjScore: 0, // 空间扣分
        cjScore: 0,   // 采集扣分
        cgScore: 0,  // 成果质量扣分
        allScore: 100, // 总分
        scoreDetailList: [], // 评分明细
        totalOutPut: 0,
        tOutPut: 0,  // 计算中的产值和占比
        tRate: 0,
        projectNo: '',
        scoreList: [],   // 分数列表
        scoreTempList: [], // 分数暂存列表
        tempRadioSum: 0, // 占比合计
        tempFileNo: '',  // 上一个文件号
        tempFileNum: 0,  // 文件数量
        fileScoreList: [],
        optChoice: '',
        options: [], // 目录
        dataList: [],
        spanArr: [],
        markScoreList: [],
        markGroupList: [],
        totalScore: 0
      }
    },
    methods: {
      init (projectNo) {
        this.projectNo = projectNo
        this.getQualityList().then(res => {
          this.tableInit(res.group)
          this.scoreDetailList = res.list
          // console.log(res.group)
          this.getMarkScoreList().then(list => {
            list.forEach((score, index) => {
              res.group.forEach(group => {
                if (score.qualityCate === group.qualityCate && score.type === group.type) {
                  group.scoreList.push({...score})
                }
              })
            })
            this.markGroupList = res.group
            this.scoreChangeHandler()
            this.loading = false
          })
        })
        this.visible = true
      },
      // 添加评分项
      addMarkScoreHandle (data) {
        console.log(data)
        this.markGroupList.forEach((item,index) => {
          if (item.qualityCate === data.qualityCate && item.type === data.type) {
            item.scoreList.push( {
              uuid: getUUID(),
              description: '',
              num: 0
            })
          }
        })
      },
      // 删除评分项
      delMarkScoreHandle (data, uuid) {
        this.markGroupList.forEach((item, index) => {
          if (item.qualityCate === data.qualityCate && item.type === data.type) {
            let scoreList = []
            item.scoreList.forEach((score, index) => {
              if (score.uuid !== uuid) {
                scoreList.push({...score})
              }
            })
            item.scoreList = scoreList
          }
        })
        this.scoreChangeHandler()
      },
      // 改变选择“评分目录”事件，则保留当前评分列表
      cateChangeHandle () {
        this.tempUpdateHandle()
        this.tempFileNo = this.optChoice[1]
        this.getDataList()
      },
      // 获取表内容
      getDataList () {
        this.getQualityFileList().then(list => {
          this.tableInit(list)
          for (let item of list) {
            for (let temp of this.scoreTempList) {
              if (temp.typeId === item.typeId) {
                item.checkA = temp.checkA
                item.checkB = temp.checkB
                item.checkC = temp.checkC
                item.checkD = temp.checkD
              }
            }
          }
          this.dataList = list
          this.scoreChangeHandler()
        })
      },
      // 获取评分文件目录
      getQualityFileList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl('/set/qualityscore/list'),
            method: 'get',
            params: this.$http.adornParams({
              fileNo: this.optChoice[1]
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.dataList = []
            }
          })
        })
      },
      /**
       * 初始化评分列表
       */
      initScoreTypeList () {
        this.scoreDetailList = []
        for (var i = 15; i < this.checkcontent.length ; i++) {
          let scoreDetail = {
            checkcontent: this.checkcontent[i],
            check_a: '',
            check_b: '',
            check_c: '',
            check_d: '',
            check_result: '',
            check_type: '',
            project_no: this.projectNo,
            score: 0,   // 扣除总分
            type_id: i + 1
          }
          this.scoreDetailList.push(scoreDetail)
        }
      },
      scoreChangeHandler () {
        this.markGroupList.forEach((item, index) => {
          let count = 0
          item.scoreList.forEach((score, index) => {
            count = count + parseInt(score.num || 0)
          })
          item.count = count

          item.itemsum =
            ((item.type === 'A' ? item.count * 42 : 0)
              + (item.type === 'B' ? item.count * 12 : 0)
              + (item.type === 'C' ? item.count * 4 : 0)
              + (item.type === 'D' ? item.count * 1 : 0))
            * parseFloat(item.scoreRadio)
        })
        this.totalScore = this.getAllScore()
        // this.initScoreListByFileNo()
        // this.tempUpdateHandle()
        // this.getScoreSumByList()
        // this.getScoreRadioSum()
      },
      // 业务员查找项
      queryDescriptionSearch (queryString, cb,item) {
        let list = []
        this.scoreDetailList.forEach((score,index) => {
          if (score.qualityCate === item.qualityCate && score.type === item.type) {
            list.push({...score})
          }
        })
        var results = queryString ? list.filter(this.descriptionFilter(queryString)) : list
        console.log(results)
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      descriptionFilter (queryString) {
        return (restaurant) => {
          return (restaurant.description.toLowerCase().indexOf(queryString.toLowerCase()) >= 0)
        }
      },
      handleDescriptionSelect (item, score) {
        score.description = item.description
      },
      // 获取评分表
      getQualityList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl('/project/qulaitymark/list'),
            method: 'get',
            params: this.$http.adornParams({})
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data)
            }
          })
        })
      },
      // 获取评分记录列表
      getMarkScoreList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl('/project/markscore/list'),
            method: 'get',
            params: this.$http.adornParams({
              projectNo: this.projectNo
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            }
          })
        })
      },
      // 获取评分列表文件
      getScoreFileList () {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl('/set/qualityscore/fileNoList'),
            method: 'get',
            params: this.$http.adornParams({})
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            }
          })
        })
      },
      // 根据项目编号获取质量评分列表(带质检表目录) 和 占比列表
      getQualityScoreVoList (projectNo) {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/project/qualityscore/volist`),
            method: 'get',
            params: this.$http.adornParams(
              { 'projectNo': projectNo }
            )
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data)
            } else {
              this.$message.error(data.msg)
              reject(data.msg)
            }
          })
        })
      },
      // 根据项目编号获取质量评分列表
      getQualityScoreList (projectNo) {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/project/qualityscore/list`),
            method: 'get',
            params: this.$http.adornParams(
              { 'projectNo': projectNo }
            )
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.$message.error(data.msg)
              reject(data.msg)
            }
          })
        })
      },
      // 根据当前项目文件编号 初始化 评分列表
      initScoreListByFileNo () {
        let cateIndex = 0
        let cateScore = 0
        // 计算每一类的扣分
        this.dataList.forEach((item, index) => {
          item.score =
            ((item.checkA === '' ? 0 : item.checkA * 42)
              + (item.checkB === '' ? 0 : item.checkB * 12)
              + (item.checkC === '' ? 0 : item.checkC * 4)
              + (item.checkD === '' ? 0 : item.checkD * 1))
            * item.scoreRadio
          cateScore += item.score
          if (index === this.spanArr.length - 1 || this.spanArr[index + 1] > 0) {
            this.dataList[cateIndex].itemsum = cateScore.toFixed(2)
            cateIndex = index + 1
            cateScore = 0
          }
        })
      },
      // 更新暂存列表
      tempUpdateHandle () {
        let tempList = []
        for (let temp of this.scoreTempList) {
          if (temp.fileNo !== this.tempFileNo) {
            tempList.push(temp)
          }
        }
        for (let item of this.dataList) {
          if (item.checkA > 0 || item.checkB > 0 || item.checkC > 0 || item.checkD > 0) {
            tempList.push(item)
          }
        }
        this.scoreTempList = tempList
      },
      // 计算评分扣除总分
      getScoreSumByList () {
        let fileItem = {}
        let fileScoreList = []
        let sum = 0
        this.scoreTempList.forEach((item, index) => {
          if (item.fileNo !== fileItem.fileNo) {
            fileScoreList.push({
              fileNo: fileItem.fileNo,
              fileName: fileItem.fileName,
              fileSum: sum
            })
            fileItem = item
            sum = 0
          }
          sum += item.score
          if (index === this.scoreTempList.length - 1) {
            fileScoreList.push({
              fileNo: item.fileNo,
              fileName: item.fileName,
              fileSum: sum
            })
          }
        })
        fileScoreList = fileScoreList.length > 1 ? fileScoreList.slice(1) : fileScoreList
        console.log(fileScoreList)
        if (this.tempFileNum === fileScoreList.length) {
          for (let index = 0;index < this.fileScoreList.length; index++) {
            fileScoreList[index].radio = this.fileScoreList[index].radio
          }
        } else {
          this.tempFileNum = fileScoreList.length
          for (let fileItem of fileScoreList) {
            fileItem.radio = (100 / this.tempFileNum).toFixed(2)
          }
        }
        this.fileScoreList = fileScoreList
      },
      // 获取评分文件占比 合计
      getScoreRadioSum () {
        let radioSum = 0
        this.fileScoreList.forEach( (item ,index) => {
          radioSum += parseFloat(item.radio)
        })
        this.tempRadioSum = Math.round(radioSum * 100) / 100
      },
      // 获取总分
      getAllScore () {
        let sum = 0
        this.markGroupList.forEach((item,index) => {
          sum += item.itemsum
        })
        return (100 - sum).toFixed(2)
      },
      // 提交评分明细
      dataFormSubmit () {
        let markList = []
        this.markGroupList.forEach((group,index) => {
          group.scoreList.forEach((score)=> {
            markList.push({
              projectNo: this.projectNo,
              qualityCate: group.qualityCate,
              scoreRadio: group.scoreRadio,
              type: group.type,
              description: score.description,
              num: score.num
            })
          })
        })
        console.log(markList)
        this.$http({
          url: this.$http.adornUrl(`/project/markscore/saveList`),
          method: 'post',
          data: this.$http.adornData({
            'markList': markList,
            'projectNo': this.projectNo,
            'qualityScore': this.totalScore
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.visible = false
            this.$emit('refreshDataList', this.totalScore)
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 表格排版
      tableInit (list) {
        this.spanArr = []
        let pos = 0
        for (let i = 0; i < list.length; i++) {
          list[i].checkA = 0
          list[i].checkB = 0
          list[i].checkC = 0
          list[i].checkD = 0
          list[i].itemsum = 0
          list[i].count = 0
          list[i].scoreList = []
          if (i === 0) {
            this.spanArr.push(1)
            pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (list[i].qualityCate === list[i - 1].qualityCate) {
              this.spanArr[pos] += 1
              this.spanArr.push(0)
            } else {
              this.spanArr.push(1)
              pos = i
            }
          }
        }
        console.log(this.spanArr)
      },
      // 合并单元格
      objectSpanMethod ({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 0 || columnIndex === 1 ) {
          const _row = this.spanArr[rowIndex]
          const _col = _row > 0 ? 1 : 0
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      },
      // 表格合计
      getSummaryMethod (param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '扣分合计：'
            return
          }
          if (index !== 0 && index !== 5) {
            sums[index] = '/'
            return
          }
          if (index === 5) {
            const values = data.map(item => Number(item[column.property]))
            let sum = 0
            for (let value of values) {
              sum += (value || 0)
            }
            sums[index] = sum.toFixed(2)
            return
          }
        })
        return sums
      },
      // 修改table header的背景色
      tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background-color: #3E8EF7;color: #fff;font-weight: 700;line-height:200%'
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "src/assets/scss/_variables.scss";
  .form_line{
    border-bottom: 1px dotted #ccc;
    border-radius: 0px;
  }
  .form_disable_item{
    border: 1px dotted #ccc;
    color: #757575;
    padding:1px;
  }
  .tab_sum {
    color: $navbar--background-color;
  }
  .title_mu {
    color: $navbar--background-color;
    font-weight: 700;
    font-size: 14px;
  }
  .form_title .from_span{
    color: black;
    font-weight: 500;
    font-size: 15px;
  }
  .item_input /deep/ .el-input__inner {
    width: 80px;
    font-weight: 700;
    color: $navbar--background-color;
  }
</style>
